<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '换绑邮箱',
  },
}
</route>
<!-- bindNewEmailBox.vue 组件 -->
<template>
  <view class="email">
    <view class="email-box">
      <!-- 新邮箱输入项 -->
      <view class="item">
        <text class="item-lable">新邮箱</text>
        <view class="item-content">
          <wd-input
            type="text"
            class="email-input"
            placeholder="请输入新邮箱"
            v-model="newEmail"
            @change="validateEmail"
          />
        </view>
      </view>

      <!-- 验证码输入项 -->
      <view class="item">
        <text class="item-lable">验证码</text>
        <view class="item-content">
          <wd-input
            type="number"
            :maxlength="6"
            class="code-input"
            placeholder="请输入六位验证码"
            v-model="verificationCode"
            @input="(e) => (verificationCode = e.detail.value.slice(0, 6))"
          />
          <view
            class="get-code"
            :class="{ disabled: countdown > 0 }"
            @click="countdown === 0 && sendVerificationCode()"
          >
            {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
          </view>
        </view>
      </view>
    </view>

    <!-- 确认按钮 -->
    <wd-button
      :custom-class="isActive ? 'custom-shadow isDisabled' : 'custom-shadow'"
      block
      @click="submitNewEmail"
    >
      确认绑定
    </wd-button>
  </view>
</template>

<script lang="ts" setup>
import { ref, watch, onUnmounted } from 'vue'
import { useUserStore } from '@/store/user'
import { getEmailCode } from '@/service/auth/index'
import { bindEmailSet } from '@/service/user/info'
import { useToast } from 'wot-design-uni'

const userStore = useUserStore()
const toast = useToast()

const newEmail = ref('')
const verificationCode = ref('')
const countdown = ref(0)
const timer = ref(null)
const isActive = ref(false)

// 邮箱验证正则
const validateEmail = () => {
  const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailReg.test(newEmail.value)
}

// 获取验证码
const sendVerificationCode = async () => {
  if (!validateEmail()) {
    return toast.error('请输入有效的邮箱地址')
  }

  try {
    toast.loading('发送中')
    const res = await getEmailCode(newEmail.value)
    toast.close()

    if (res.code === 200) {
      toast.success('验证码已发送')
      startCountdown()
    } else {
      toast.error(res.message || '发送失败')
    }
  } catch (error) {
    toast.error('验证码发送失败')
  }
}

// 倒计时逻辑
const startCountdown = () => {
  countdown.value = 60
  timer.value = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else if (timer.value) {
      clearInterval(timer.value)
      timer.value = null
    }
  }, 1000)
}

// 提交绑定
const submitNewEmail = async () => {
  if (!validateEmail()) return toast.error('邮箱格式错误')
  if (!/^\d{6}$/.test(verificationCode.value)) return toast.error('验证码格式错误')

  try {
    toast.loading('绑定中')
    const res = await bindEmailSet({
      email: newEmail.value,
      code: verificationCode.value,
    })

    if (res.code === 200) {
      userStore.setToken(res.data)
      await userStore.getUserInfo()
      toast.show('绑定成功')
      uni.navigateBack()
    } else {
      toast.show(res.message || '绑定失败')
    }
  } catch (error) {
    toast.show('绑定请求异常')
  } finally {
    toast.close()
  }
}

// 按钮状态监听
watch([newEmail, verificationCode], ([email, code]) => {
  isActive.value = validateEmail() && /^\d{6}$/.test(code)
})

// 组件卸载清除定时器
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
})
</script>

<style lang="scss" scoped>
.email {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f5f5f5;

  .email-box {
    display: flex;
    flex-direction: column;
    width: 100%;
    max-width: 680rpx;
    padding: 20rpx;
    margin-bottom: 15rpx;
    background-color: #ffffff;
    border-radius: 10rpx;

    .item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20rpx;

      .item-lable {
        width: 120rpx;
        font-size: 24rpx;
        color: #333;
      }

      .item-content {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 540rpx;
        line-height: 1.5;

        .email-input,
        .code-input {
          flex: 1;
          padding: 10rpx;
          font-size: 24rpx;
        }

        .get-code {
          width: 110rpx !important;
          padding: 10rpx;
          font-size: 20rpx;
          color: white;
          text-align: center;
          background-color: $uni-bg-themes;
          border-radius: 10rpx;

          &.disabled {
            pointer-events: none;
            opacity: 0.6;
          }
        }
      }

      &:last-child .item-content::before {
        content: none;
      }
    }
  }

  :deep() {
    .custom-shadow {
      width: 680rpx;
      color: #fff;
      background-color: $uni-bg-themes;
      opacity: 0.6;
    }

    .isDisabled {
      background-color: $uni-bg-themes;
      opacity: 1;
    }
  }
}
</style>
